package cn.display.pixelworksx7.util

import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.content.res.Resources
import android.util.Log
import cn.display.pixelworksx7.constant.GlobalData
import cn.display.pixelworksx7.data.AppConfigInfo
import cn.display.pixelworksx7.data.AppConfigInfoFile
import org.w3c.dom.Document
import org.w3c.dom.Element
import java.io.File
import javax.xml.parsers.DocumentBuilder
import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.transform.OutputKeys
import javax.xml.transform.Transformer
import javax.xml.transform.TransformerFactory
import javax.xml.transform.dom.DOMSource
import javax.xml.transform.stream.StreamResult
import kotlin.streams.toList

class IrisConfigUtil {
    companion object {
        // 配置文件路径
        var irisConfigFilePath = "/sdcard/irisConfig.xml"
        var irisConfigBinFilePath = "/odm/bin/irisConfig"
        val irisConfigListId = "iris_config_list"
        val tag :String = "IrisConfigUtil"
        // 视频默认配置s
        var videoDefaultIrisConfig = listOf<String>(
            "258 4 40 -1 34 -1 3 120",
            "273 2 1 3"
        )
        // 获取本机第三方软件
        fun getAppInfoList(packageManager: PackageManager): List<AppConfigInfo> {
            val applicationInfoList = packageManager.getInstalledApplications(0).stream()
                // 过滤掉系统软件
                .filter { (it.flags and ApplicationInfo.FLAG_SYSTEM) <= 0 }
                .toList()
            // 解析并生成对应数据
            var appConfigInfoLists: List<AppConfigInfo> = applicationInfoList.map { applicationInfo: ApplicationInfo ->
                AppConfigInfo(
                    applicationInfo.packageName,// 包名
                    applicationInfo.loadLabel(packageManager).toString(), // 软件名
                    applicationInfo.loadIcon(packageManager),//图标
                    null             // irisConfig 参数
                )
            }
            return appConfigInfoLists
        }
        //  禁用iris
        fun disableIris() {
            var disableIrisCommands = arrayOf<String>("/odm/bin/irisConfig 47 1 0" +
                    "/odm/bin/irisConfig 258 1 0" +
                    "/odm/bin/irisConfig 267 2 3 0" +
                    "/odm/bin/irisConfig 273 1 0")
            ShellUtil.execCommand(disableIrisCommands, true)
        }
        // 添加配置
        fun addIrisConfig(appConfigInfo: AppConfigInfoFile) : Int{
           // Log.w(tag,"appConfigInfo.params" + appConfigInfo.params);
            try {
                var document = getIrisCOnfigFileDocument()
                // 获取子节点
                var irisConfigNode = document.getElementById(appConfigInfo.packageName)
                var params = appConfigInfo.params
                if (irisConfigNode != null) {
                    // 先获取文件里的参数
                    // 删除配置
                    if (params.size==0) {
                        val irisConfigListE: Element = getIrisConfigListElement(document)
                        irisConfigListE.removeChild(irisConfigNode)
                    } else {
                        val irisConfigListE: Element = getIrisConfigListElement(document)
                        irisConfigListE.removeChild(irisConfigNode)
                        irisConfigNode = document.createElement("iris_config")
                        irisConfigNode.setAttribute("id", appConfigInfo.packageName)
                        // 设置参数
                        for (index in 0..params.size - 1) {
                            val irisConfigParamsE: Element = document.createElement("params")
                            irisConfigParamsE.textContent = params.get(index)
                            irisConfigNode.appendChild(irisConfigParamsE)
                        }
                        irisConfigListE.appendChild(irisConfigNode)
                    }
                } else {
                    // 根节点
                    val irisConfigListE: Element = getIrisConfigListElement(document)
                    // 创建单个配置节点
                    irisConfigNode = document.createElement("iris_config")
                    irisConfigNode.setAttribute("id", appConfigInfo.packageName)
                    // 设置参数
                    for (index in 0..params.size - 1) {
                        val irisConfigParamsE: Element = document.createElement("params")
                        irisConfigParamsE.textContent = params.get(index)
                        irisConfigNode.appendChild(irisConfigParamsE)
                    }
                    irisConfigListE.appendChild(irisConfigNode)
                }
                documentWriteIrisConfigFile(document)
                loadIrisConfigFileParseToMap()
                GlobalData.lastTopPackageName = ""
                return 1
            }catch (e:Exception) {
                return 0
            }
        }

        // init irisConfig file
        fun initIrisConfigFile() {
            // 创建文档构建工厂
            val documentBuilderFactory: DocumentBuilderFactory = DocumentBuilderFactory.newInstance()
            // 创建文档构建
            var documentBuilder: DocumentBuilder? = null
            documentBuilder = documentBuilderFactory.newDocumentBuilder()
            // 先获取文档
            val document: Document = documentBuilder.newDocument()
            document.setXmlStandalone(true)
            document.setXmlVersion("1.0")
            // 根节点
            val irisConfigListE: Element = document.createElement("iris_config_list")
            irisConfigListE.setAttribute("id","iris_config_list")
            document.appendChild(irisConfigListE)
            documentWriteIrisConfigFile(document)
        }
        // 读取文件配置解析成map
        fun loadIrisConfigFileParseToMap(){
            var exists = File(irisConfigFilePath).exists()
            if (!exists) {
                initIrisConfigFile()
            }
            var document = getIrisCOnfigFileDocument()
            val irisConfigMap: MutableMap<String, List<String>> = mutableMapOf()
            var childNodes = document.getElementsByTagName("iris_config")
            for (childNodesIndex in 0..childNodes.length-1) {
                var paramsList = mutableListOf<String>()
                var irisConfigNode = childNodes.item(childNodesIndex)
                var attributes = irisConfigNode.attributes
                var paramsNodes = irisConfigNode.childNodes
                for (paramsNodesIndex in 0..paramsNodes.length-1) {
                    var textContent = paramsNodes.item(paramsNodesIndex).textContent
                    if (!textContent.trim().equals("")) {
                        paramsList.add(textContent)
                    }
                }
                var packageName  = ""
                for (attributesIndex in 0..attributes.length-1) {
                   val attribute  =  attributes.item(attributesIndex)
                    if (attribute.nodeName.equals("id")) {
                        packageName = attribute.nodeValue
                        break
                    }
                }
               // Log.e(tag ,"--" + packageName + "--params--" + paramsList)
                irisConfigMap.put(packageName,paramsList)
            }
            GlobalData.irisConfigMap = irisConfigMap
        }
        // val irisConfigListE: Element =
        fun getIrisConfigListElement (document: Document) : Element {
            return document.getElementById(irisConfigListId)
        }
        fun getIrisCOnfigFileDocument () :Document {
            // 创建文档构建工厂
            val documentBuilderFactory: DocumentBuilderFactory = DocumentBuilderFactory.newInstance()
            // 创建文档构建
            var documentBuilder: DocumentBuilder? = null
            documentBuilder = documentBuilderFactory.newDocumentBuilder()
            // 先获取文档
            val document: Document = documentBuilder.parse(File(irisConfigFilePath))
            return document
        }
        // 文档写入到文件
        fun documentWriteIrisConfigFile (document: Document) {
            var tff: TransformerFactory = TransformerFactory.newInstance();
            // 创建一个Transformer的对象
            var tf: Transformer = tff.newTransformer();
            // 输出内容是否使用换行
            tf.setOutputProperty(OutputKeys.INDENT, "yes");
            // 创建xml文件并写入内容
            tf.transform(DOMSource(document), StreamResult(File(irisConfigFilePath)));
        }
        // 通过包名获取其参数
        fun getIrisConfigByPackageName (packageName : String) : List<String>{
            var paramsList = mutableListOf<String>()
            var irisCOnfigFileDocument = getIrisCOnfigFileDocument()
            var irisConfigElement = irisCOnfigFileDocument.getElementById(packageName)
            // 没有对应的参数
            if (irisConfigElement==null) {
                return paramsList
            }
            var paramsNodes = irisConfigElement.getElementsByTagName("params")
           // System.err.println("paramsNodes" + paramsNodes.length)
            for (paramsNodesIndex in 0..paramsNodes.length-1) {
                val paramsNode = paramsNodes.item(paramsNodesIndex)
                // System.err.println(paramsNode.textContent)
                paramsList.add(paramsNode.textContent)
            }
           // System.err.println(paramsList + "--size--" + paramsList.size)
            return paramsList
        }
    }
}
